<template>
    <div style="padding-bottom: 80px">
      <el-row>
        <!-- 纸类图片上传 -->
        <el-col :span="12" style="padding: 40px;">
          <el-card  style="margin:0 auto;padding-bottom: 20px;">
            <div slot="header">
                <el-input
                    type="text"
                    placeholder="请输入类别一"
                    v-model="category1"
                    style="width: 200px;text-align: center;"
                    class="cagetoryInput"
                >
                </el-input>

                <el-button style="float: right; padding: 3px 0" type="text">...</el-button>
            </div>
            <div class="text item">
              <input type="file" id="userFile_Paper" multiple = "multiple" @change="countPaper" hidden>
              <p v-if="paper_total==0">在这里添加你的图片</p>
              <div v-else style="overflow: auto; max-height: 108px;">
                <div v-for="(item, index) in paperImgs" :key="index" style="display: inline-block;margin: 0px 5px;position:relative;">
                  <img :id= "'paper'+index" :src=item style="height: 50px; width: 50px;" >
                  <i class="el-icon-close" @click="deletePaperImg(index)" style="width:15px;height:15px;background-color: gainsboro;line-height:15px;border-radius: 5px;position:absolute;float:right;top:0px;right:0px;display:block;"></i>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div>
              <span style="float:left;font-size: 10px">共计 {{paper_total}} 张</span>
              <div style="float:right">
                <el-button @click="clearPaperPicture">清空</el-button>
                <el-button @click="addPaperPicture" multiple = "multiple" type="primary">添加</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        <!-- 塑料图片上传 -->
        <el-col :span="12" style="padding: 40px;">
          <el-card  style="margin: 0px auto;padding-bottom: 20px">
            <div slot="header" class="clearfix">
                <el-input
                type="text"
                placeholder="请输入类别二"
                v-model="category2"
                style="width: 200px;"
                class="cagetoryInput"
                >
                </el-input>
              <el-button style="float: right; padding: 3px 0" type="text">...</el-button>
            </div>
            <div class="text item">
              <input type="file" id="userFile_Plastic" multiple = "multiple" @change="countPlastic" hidden>
              <p v-if="plastic_total==0">在这里添加你的图片</p>
              <div v-else style="overflow: auto; max-height: 108px;">
                <div v-for="(item, index) in plasticImgs" :key="index" style="display: inline-block;margin: 0px 5px;position:relative;">
                  <img :id="'plastic'+index" :src=item style="height: 50px;width: 50px;">
                  <i class="el-icon-close" @click="deletePlasticImg(index)"  style="width:15px;height:15px;background-color: gainsboro;line-height:15px;border-radius: 5px;position:absolute;float:right;top:0px;right:0px;display:block;"></i>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div>
              <span style="float:left;font-size: 10px">共计 {{plastic_total}} 张</span>
              <div style="float:right">
                <el-button @click="clearPlasticPicture">清空</el-button>
                <el-button @click="addPlasticPicture" multiple = "multiple" type="primary">添加</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <!-- 玻璃图片上传 -->
        <el-col :span="12" style="padding: 40px;">
          <el-card style="margin:0 auto;padding-bottom: 20px;">
            <div slot="header">
                <el-input
                type="text"
                placeholder="请输入类别三"
                v-model="category3"
                style="width: 200px;"
                class="cagetoryInput"
                >
                </el-input>
              <el-button style="float: right; padding: 3px 0" type="text">...</el-button>
            </div>
            <div class="text item">
              <input type="file" id="userFile_Glass" multiple = "multiple" @change="countGlass" hidden>
              <p v-if="glass_total==0">在这里添加你的图片</p>
              <div v-else style="overflow: auto; max-height: 108px;">
                <div v-for="(item, index) in glassImgs" :key="index" style="display: inline-block;margin: 0px 5px;position:relative;">
                  <img :id="'glass'+index" :src=item style="height: 50px;width: 50px;">
                  <i class="el-icon-close" @click="deleteGlassImg(index)"  style="width:15px;height:15px;background-color: gainsboro;line-height:15px;border-radius: 5px;position:absolute;float:right;top:0px;right:0px;display:block;"></i>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div>
              <span style="float:left;font-size: 10px">共计 {{glass_total}} 张</span>
              <div style="float:right">
                <el-button @click="clearGlassPicture">清空</el-button>
                <el-button @click="addGlassPicture" multiple = "multiple" type="primary">添加</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
        <!-- 厨余图片上传 -->
        <el-col :span="12" style="padding: 40px;">
          <el-card  style="margin: 0px auto;padding-bottom: 20px">
            <div slot="header" class="clearfix">
                <el-input
                type="text"
                placeholder="请输入类别四"
                v-model="category4"
                style="width: 200px;"
                class="cagetoryInput"
                >
                </el-input>
              <el-button style="float: right; padding: 3px 0" type="text">...</el-button>
            </div>
            <div  class="text item">
              <input type="file" id="userFile_Kitchen" multiple = "multiple" @change="countKitchen" hidden>
              <p v-if="kitchen_total==0">在这里添加你的图片</p>
              <div v-else style="overflow: auto; max-height: 108px;">
                <div v-for="(item, index) in kitchenImgs" :key="index" style="display: inline-block;margin: 0px 5px;position:relative;">
                  <img :id="'kitchen'+index" :src=item style="height: 50px;width: 50px;">
                  <i class="el-icon-close" @click="deleteKitchenImg(index)" style="width:15px;height:15px;background-color: gainsboro;line-height:15px;border-radius: 5px;position:absolute;float:right;top:0px;right:0px;display:block;"></i>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div>
              <span style="float:left;font-size: 10px">共计 {{kitchen_total}} 张</span>
              <div style="float:right">
                <el-button @click="clearKitchenPicture">清空</el-button>
                <el-button @click="addKitchenPicture" multiple = "multiple" type="primary">添加</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" >
          <el-card style="width: 90%;margin: 0 auto;padding:20px;padding-bottom: 50px">
            <div slot="header" class="clearfix">
              <span>模型构建</span>
            </div>
            <el-row>
              <el-col :span="12" style="border-right:1px dashed grey">
                <div style="transform: translateX(12px)">
                  <span >模型类型：</span>
                  <div style="display: inline-block">
                    <el-radio-group  v-model="radio1" @change="ParmChange">
                      <el-radio label="1"  border>简单模型</el-radio>
                      <el-radio style="transform: translateX(-35px)" label="2" border>复杂模型</el-radio>
                    </el-radio-group>
                  </div>
                </div>
                <div v-if="showParmKind"  id="SimpleParam">
                  <div style="margin-top: 10px;">
                    <span>网络模型：</span>
                    <el-select v-model="fullLayerValue" placeholder="选择模型层数" @change="showSModel">
                      <!-- 用户选择哪种全连接层，通过fullLayerValue进行数据绑定 -->
                      <el-option style="font-size: 18px; height: 50px;line-height: 50px;" v-for="(item, index) in fullLayers" :key="index" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                    <el-button type="text" @click="introModel(1)" icon="el-icon-question"></el-button>
                    <div style="margin-top: 10px;">
                      <span>激活函数：</span>
                      <el-select v-model="activation1" placeholder="选择激活函数">
                        <!-- 用户选择哪种全连接层，通过fullLayerValue进行数据绑定 -->
                        <el-option style="font-size: 18px; height: 50px;line-height: 50px;" v-for="(item, index) in selectActivation1" :key="index" :value="item.value" :label="item.label"></el-option>
                      </el-select>
                      <el-button type="text" @click="introActivation" icon="el-icon-question"></el-button>
                    </div>
                    <div style="margin-top: 5px;">
                      <div style="transform: translateX(7px)">
                        <span>学习率：</span>
                        <el-input-number class="numInput" size="medium" v-model="setLearnRate" controls-position="right" :step="0.0001" :min="0.0008" :max="0.003"></el-input-number>
                        <el-button type="text" @click="introRate" icon="el-icon-question"></el-button>
                      </div>
                      <div style="margin-top:5px;transform: translateX(9px)">
                        <span>epoch：</span>
                        <el-input-number class="numInput" size="medium" v-model="setEpoch" controls-position="right" :min="10" :max="50"></el-input-number>
                        <el-button type="text" @click="introEpoch" icon="el-icon-question"></el-button>
                      </div>
                      <div style="margin-top:5px;transform: translateX(-5px)">
                        <span>batchSize：</span>
                        <el-input-number class="numInput" size="medium" v-model="setBatchSize" controls-position="right" :min="15" :max="50"></el-input-number>
                        <el-button type="text" @click="introBatchSize" icon="el-icon-question"></el-button>
                      </div>
                    </div>
                    <div style="margin-top: 20px;">
                      <el-button @click="createSimpleModel" multiple = "multiple" type="primary">简单模型构建</el-button>
                      <div v-if="simpleModelAcc > 0">模型准确率:{{simpleModelAcc}}%</div>
                    </div>
                  </div>
                </div>
                <div v-else id="ComplexModel" >
                  <div style="margin-top: 10px;">
                    <span>网络模型：</span>
                    <el-select v-model="convoNetValue" placeholder="选择模型层数" @change="showCModel">
                      <!-- 用户选择哪种卷积神经网络，通过convoNetValue进行数据绑定 -->
                      <el-option style="font-size: 18px; height: 50px;line-height: 50px;" v-for="(item, index) in convoNetLayers" :key="index" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                    <el-button type="text" @click="introModel(2)" icon="el-icon-question"></el-button>
                  </div>
                  <div style="margin-top: 10px;">
                    <span>激活函数：</span>
                    <el-select v-model="activation2" placeholder="选择激活函数">
                      <!-- 用户选择哪种卷积神经网络，通过convoNetValue进行数据绑定 -->
                      <el-option style="font-size: 18px; height: 50px;line-height: 50px;" v-for="(item, index) in selectActivation2" :key="index" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                    <el-button type="text" @click="introActivation" icon="el-icon-question"></el-button>
                  </div>
                  <div style="margin-top: 5px;">
                    <div style="transform: translateX(7px)">
                      <span >学习率：</span>
                      <el-input-number class="numInput" size="medium" v-model="setLearnRate1" controls-position="right" :step="0.0001" :min="0.0008" :max="0.003"></el-input-number>
                      <el-button type="text" @click="introRate" icon="el-icon-question"></el-button>
                    </div>
                    <div style="margin-top:5px;transform: translateX(9px)">
                      <span>epoch：</span>
                      <el-input-number class="numInput" size="medium" v-model="setEpoch1" controls-position="right" :min="10" :max="50"></el-input-number>
                      <el-button type="text" @click="introEpoch" icon="el-icon-question"></el-button>
                    </div>
                    <div style="margin-top:5px;transform: translateX(-5px)">
                      <span>batchSize：</span>
                      <el-input-number class="numInput" size="medium" v-model="setBatchSize1" controls-position="right" :min="15" :max="50"></el-input-number>
                      <el-button type="text" @click="introBatchSize" icon="el-icon-question"></el-button>
                    </div>
                  </div>
                  <div style="margin-top: 20px;">
                    <el-button @click="createComplexModel" multiple = "multiple" type="primary">复杂模型构建</el-button>
                    <div v-if="simpleModelAcc1 > 0">模型准确率:{{simpleModelAcc1}}%</div>
                  </div>
                </div>
              </el-col>

              <el-col :span="12">
                <span>模型结构</span>
                <div v-if="showParmKind" class="showModel">
                  <div>
                    <img src="https://oktools.net/ph/438x350?t=简单模型结构" id="showSimpleModel" style="width: 456px; height: 315px;">
                  </div>
                </div>
                <div  v-else class="showModel">
                  <div>
                    <img src="https://oktools.net/ph/438x350?t=复杂模型结构" id="showComplexModel" style="width: 456px; height: 315px;">
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>


<!--      <el-row>-->

<!--        <el-col :span="8" style="padding:40px;">-->
<!--          <el-card style="width: 480px;margin:70px auto;">-->
<!--            <div>-->
<!--              <span>模型测试</span>-->
<!--            </div>-->
<!--            <div class="showImg">-->
<!--              <div >-->
<!--                <img src="https://oktools.net/ph/438x350?t=上传的图片会显示在这里" id="testImg" style="width: 438px; height: 350px; border-radius: 10px;">-->
<!--              </div>-->
<!--            </div>-->
<!--            <div style="display: inline-block;">-->
<!--              <el-select v-model="selectModelValue" placeholder="选择测试模型">-->
<!--                &lt;!&ndash; 用户选择简单模型或者复杂模型进行测试，通过selectModelValue判断选择哪个模型 &ndash;&gt;-->
<!--                <el-option style="font-size: 18px; height: 50px;line-height: 50px;" v-for="(item, index) in selectModel" :key="index" :value="item.value" :label="item.label"></el-option>-->
<!--              </el-select>-->
<!--            </div>-->
<!--            <div class="chooseImg">-->
<!--              <input type="file" id="userFile" @change="handleSelect" hidden>-->
<!--              <el-button  @click="triggerFileSelect" type="primary">选择测试图片</el-button>-->
<!--            </div>-->

<!--          </el-card>-->
<!--          <h2>识别结果：{{showResult}}</h2>-->
<!--        </el-col>-->
<!--      </el-row>-->

          <el-dialog

        :visible.sync="centerDialogVisible"
        width="30%"
        :close-on-click-modal = "false"
        :close-on-press-escape = "false"
        :show-close = "false"
        :center = "true"
        style="margin-top: 160px;"
        >
        <div style="text-align: center;">
          <img src="../../assets/img/loading.gif" width="200px" alt="">
          <h2>模型训练中，请稍等！</h2>
        </div>
      </el-dialog>
    </div>
  </template>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.4.0/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@1.0.2/dist/tfjs-vis.umd.min.js"></script>
  <script src="../../assets/js/createModel.js"></script>
  <script>

  import * as tf from '@tensorflow/tfjs'
  import {createSimpleModel, createComplexModel} from '../../assets/js/createModel.js'
  const axios = require('axios');
  import qs from "qs"
  import lrz from 'lrz'


  export default {
    name: "Dog_vs_Cat",
    data(){
      return{
        user_info:{
          id:"",
          nickname:""
        },
        radio1:"1",
        showParmKind:true,
        centerDialogVisible:false,
        category1:'易拉罐',
        category2:'键盘',
        category3:'电池',
        category4:'纸',

        setLearnRate:'',
        setEpoch:'',
        setBatchSize:'',

        setLearnRate1:'',
        setEpoch1:'',
        setBatchSize1:'',

        active: 1,
        paperImgs:[],
        plasticImgs:[],
        glassImgs:[],
        kitchenImgs:[],
        paper_total:0,
        plastic_total:0,
        glass_total:0,
        kitchen_total:0,
        fullLayerValue:'',
        // 简单模型激活函数
        activation1:'',
        selectActivation1:[
          { value:'relu', label:'relu激活函数'},
          { value:'sigmoid', label:'sigmoid激活函数'},
          { value:'tanh', label:'tanh激活函数'},
        ],
        fullLayers:[
          { value:'3', label:'3层全连接网络'},
          { value:'4', label:'4层全连接网络'},
          { value:'5', label:'5层全连接网络'},
        ],
        convoNetValue:'',
        // 复杂模型激活函数
        activation2:'',
        selectActivation2:[
          { value:'relu', label:'relu激活函数'},
          { value:'sigmoid', label:'sigmoid激活函数'},
          { value:'tanh', label:'tanh激活函数'},
        ],
        convoNetLayers:[
          { value:'3', label:'3层卷积神经网络'},
          { value:'4', label:'4层卷积神经网络'},
          { value:'5', label:'5层卷积神经网络'},
        ],
        simpleModelValue:'',
        dialogVisible: false,
        showCat:false,
        showIndex:true,
        showImgSrc:'',
        selectModelValue:'',
        selectModel:[
          { value:'1', label:'简单模型'},
          { value:'2', label:'复杂模型'},
        ],
        //简单模型
        model1:'',
        //复杂模型
        model2:'',
        //训练完成的简单模型
        model3:{},
        //训练完成的复杂模型
        model4:{},
        simpleModelAcc:0,
        simpleModelAcc1:0,
        //模型预测结果
        showResult:'',
        //模型图片
        modelImgs:{
            dense3:require("../../assets/img/3full.png"),
            dense4:require("../../assets/img/4full.png"),
            dense5:require("../../assets/img/5full.png"),
            cnn3:require("../../assets/img/3cnn.png"),
            cnn4:require("../../assets/img/4cnn.png"),
            cnn5:require("../../assets/img/5cnn.png"),
        }
      }
    },
    methods:{
      addPaperPicture(){
        var btn=document.getElementById("userFile_Paper")
        btn.click()
      },
      addPlasticPicture(){
        var btn=document.getElementById("userFile_Plastic")
        btn.click()
      },
      addGlassPicture(){
        var btn=document.getElementById("userFile_Glass")
        btn.click()
      },
      addKitchenPicture(){
        var btn=document.getElementById("userFile_Kitchen")
        btn.click()
      },
      countPaper(e){
        var len = e.target.files.length;
        var file = document.getElementById('userFile_Paper').files;
        this.$data.paper_total += e.target.files.length;
        let _this = this;
        for (let i= 0; i< e.target.files.length; i++) {

          lrz( file[i], {
            with: 56, // 图片最大的宽度。默认为原图的宽度
            height: 56, // 图片最大的高度，默认为原图的高度
            quality: 0.1, // 图片压缩质量，取值0-1，默认为0.7
            filedName: '', // 后端接收的字段名，默认为 'file'
          }).then( (rst) => {
            // 处理成功会执行
            var _this = this;
              // 回显图片
              _this.paperImgs.push(rst.base64);
            // console.log(rst.file.size / 1024, 'kb'); // 压缩后
          })
          .catch(function (err) {
              // 处理失败会执行
          })
          .always(function () {
              // 不管是成功失败，都会执行
          });
        }
      },
      countPlastic(e){
        var len = e.target.files.length;
        var file = document.getElementById('userFile_Plastic').files;
        this.$data.plastic_total += e.target.files.length;
        let _this = this;
        for (let i= 0; i< e.target.files.length; i++) {

          lrz( file[i], {
            with: 56, // 图片最大的宽度。默认为原图的宽度
            height: 56, // 图片最大的高度，默认为原图的高度
            quality: 0.1, // 图片压缩质量，取值0-1，默认为0.7
            filedName: '', // 后端接收的字段名，默认为 'file'
          }).then( (rst) => {
            // 处理成功会执行
            var _this = this;
              // 回显图片
              _this.plasticImgs.push(rst.base64);
            // console.log(rst.file.size / 1024, 'kb'); // 压缩后
          })
          .catch(function (err) {
              // 处理失败会执行
          })
          .always(function () {
              // 不管是成功失败，都会执行
          });
        }
      },
      countGlass(e){
        var len = e.target.files.length;
        var file = document.getElementById('userFile_Glass').files;
        this.$data.glass_total += e.target.files.length;
        let _this = this;
        for (let i= 0; i< e.target.files.length; i++) {

          lrz( file[i], {
            with: 56, // 图片最大的宽度。默认为原图的宽度
            height: 56, // 图片最大的高度，默认为原图的高度
            quality: 0.1, // 图片压缩质量，取值0-1，默认为0.7
            filedName: '', // 后端接收的字段名，默认为 'file'
          }).then( (rst) => {
            // 处理成功会执行
            var _this = this;
              // 回显图片
              _this.glassImgs.push(rst.base64);
            // console.log(rst.file.size / 1024, 'kb'); // 压缩后
          })
          .catch(function (err) {
              // 处理失败会执行
          })
          .always(function () {
              // 不管是成功失败，都会执行
          });
        }
      },
      countKitchen(e){
        var len = e.target.files.length;
        var file = document.getElementById('userFile_Kitchen').files;
        this.$data.kitchen_total += e.target.files.length;
        let _this = this;
        for (let i= 0; i< e.target.files.length; i++) {
          lrz( file[i], {
            with: 56, // 图片最大的宽度。默认为原图的宽度
            height: 56, // 图片最大的高度，默认为原图的高度
            quality: 0.1, // 图片压缩质量，取值0-1，默认为0.7
            filedName: '', // 后端接收的字段名，默认为 'file'
          }).then( (rst) => {
            // 处理成功会执行
            var _this = this;
            // 回显图片
            _this.kitchenImgs.push(rst.base64);
            // console.log(rst.file.size / 1024, 'kb'); // 压缩后
          })
          .catch(function (err) {
              // 处理失败会执行
          })
          .always(function () {
              // 不管是成功失败，都会执行
          });
        }
      },

      clearPaperPicture(){
        this.$data.paper_total = 0;
        this.$data.paperImgs = [];
      },
      clearPlasticPicture(){
        this.$data.plastic_total = 0;
        this.$data.plasticImgs = [];
      },
      clearGlassPicture(){
        this.$data.glass_total = 0;
        this.$data.glassImgs = [];
      },
      clearKitchenPicture(){
        this.$data.kitchen_total = 0;
        this.$data.kitchenImgs = [];
      },

      deletePaperImg(index){
        this.$data.paperImgs.splice(index,1);
        this.$data.paper_total = this.$data.paper_total - 1;
      },
      deletePlasticImg(index){
        this.$data.plasticImgs.splice(index,1);
        this.$data.plastic_total = this.$data.plastic_total - 1;
      },
      deleteGlassImg(index){
        this.$data.glassImgs.splice(index,1);
        this.$data.glass_total = this.$data.glass_total - 1;
      },
      deleteKitchenImg(index){
        this.$data.kitchenImgs.splice(index,1);
        this.$data.kitchen_total = this.$data.kitchen_total - 1;
      },

      showSModel(){
          var img = document.getElementById("showSimpleModel");
        if(this.$data.fullLayerValue==3){
            img.src=this.$data.modelImgs.dense3;
        }else if(this.$data.fullLayerValue==4){
            img.src=this.$data.modelImgs.dense4;
        }else{
            img.src=this.$data.modelImgs.dense5;
        }
      },
      showCModel(){
          var img = document.getElementById("showComplexModel");
        if(this.$data.convoNetValue==3){
            img.src= this.$data.modelImgs.cnn3;
        }else if(this.$data.convoNetValue==4){
            img.src=this.$data.modelImgs.cnn4;
        }else{
            img.src= this.$data.modelImgs.cnn5;
        }
      },

      //介绍概念
      introModel(index){
        if(index==1){
          this.$alert('全连接网络结构是最基本的神经网络/深度神经网络层，全连接层的每一个节点都与上一层的所有节点相连。全连接层在早期主要用于对提取的特征进行分类，然而由于全连接层所有的输出与输入都是相连的，一般全连接层的参数是最多的，这需要相当数量的存储和计算空间。参数的冗余问题使单纯的常规神经网络很少会被应用于较为复杂的场景中。常规神经网络一般用于依赖所有特征的简单场景，比如说房价预测模型和在线广告推荐。', '全连接网络', {
            confirmButtonText: '关闭',
          });
        }else{
          this.$alert('卷积神经网络（CNN）是一种专门用来处理具有类似网格结构的数据的神经网络，如图像数据（可以看作二维的像素网格）。与全连接网络不同的地方在于，CNN的上下层神经元并不都能直接连接，而是通过“卷积核”作为中介，通过“核”的共享大大减少了隐藏层的参数。简单的CNN是一系列层，并且每个层都通过一个可微函数将一个量转化为另一个量，这些层主要包括卷积层（Convolutional Layer）、池化层（Pooling Layer）和全连接层（FC Layer）。卷积网络在诸多应用领域都有很好的应用效果，特别是在大型图像处理的场景中表现得格外出色。', '卷积神经网络', {
            confirmButtonText: '关闭',
          });
        }
      },
      introActivation(){
        this.$alert('神经网络中的每个神经元节点接受上一层神经元的输出值作为本神经元的输入值，并将输入值传递给下一层，输入层神经元节点会将输入属性值直接传递给下一层（隐层或输出层）。在多层神经网络中，上层节点的输出和下层节点的输入之间具有一个函数关系，这个函数称为激活函数（又称激励函数）。', '激活函数', {
          confirmButtonText: '关闭',
        });
      },
      introRate(){
        this.$alert('学习率(Learning rate)作为监督学习以及深度学习中重要的超参，其决定着目标函数能否收敛到局部最小值以及何时收敛到最小值。合适的学习率能够使目标函数在合适的时间内收敛到局部最小值。', '学习率', {
          confirmButtonText: '关闭',
        });
      },
      introEpoch(){
        this.$alert('一个Epoch就是将所有训练数据集训练一次的过程。', 'epoch', {
          confirmButtonText: '关闭',
        });
      },
      introBatchSize(){
        this.$alert('每次训练的数据集大小。', 'batchSize', {
          confirmButtonText: '关闭',
        });
      },

      //创建简单模型
      createSimpleModel(){
        //获取模型训练开始的时间戳
        let time1 = new Date().getTime();

        //显示加载动画
        this.$data.centerDialogVisible = true;
        //将数据发给模型测试组件
        var category = {
          catg_1:this.$data.category1,
          catg_2:this.$data.category2,
          catg_3:this.$data.category3,
          catg_4:this.$data.category4,
        }

        console.log(this.$data.fullLayerValue);
        console.log(this.$data.activation1);

        //存储图片标签
        axios.post('http://192.168.31.103:2444/CatgCenter/uploadMyCategory', qs.stringify(category))
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });

        // 创建简单模型
        if(this.$data.fullLayerValue == 3){
          //创建3层全连接网络
          this.$data.model1 = createSimpleModel(3, this.$data.activation1);
        }else if(this.$data.fullLayerValue == 4){
          //创建4层全连接网络
          this.$data.model1 = createSimpleModel(4, this.$data.activation1);
        }else{
          //创建5层全连接网络
          this.$data.model1 = createSimpleModel(5, this.$data.activation1);
        }


        //获取返回创建的模型
        var model = this.$data.model1;

        //简单模型训练过程
        //加载图片数据
        //训练集张量
        var paperTensor;
        var plasticTensor;
        var glassTensor;
        var kitchenTensor;

        //验证集张量
        var paperTensor1;
        var plasticTensor1;
        var glassTensor1;
        var kitchenTensor1;

        //训练集
        var paperArray = [];
        var plasticArray = [];
        var glassArray = [];
        var kitchenArray = [];
        //验证集
        var paperArray1 = [];
        var plasticArray1 = [];
        var glassArray1 = [];
        var kitchenArray1 = [];

        var paperLength = this.$data.paperImgs.length;
        var plasticLength = this.$data.plasticImgs.length;
        var glassLength = this.$data.glassImgs.length;
        var kitchenLength = this.$data.kitchenImgs.length;

        //所有图片的张量
        var traTensor; //训练集
        var valTensor; //测试集
        //训练集标签
        var labelTensor = [];
        //验证集标签
        var labelTensor1 = [];

        //图片数据获取并转换为张量
        //纸类图片转换张量
        var paperLen = parseInt(0.8*paperLength); //训练集长度
        for (var i = 0; i < paperLength; i++) {
          var img = document.getElementById('paper'+i);
          let imgTensor =tf.browser.fromPixels(img);
          // console.log(imgTensor);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();

          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);
          if(i < paperLen){
            //训练集
            paperArray.push(tensor);
            labelTensor.push(1,0,0,0);
          }else{
            //验证集
            paperArray1.push(tensor)
            labelTensor1.push(1,0,0,0);
          }
        }
        //训练集张量
        paperTensor = tf.concat(paperArray,0);
        //验证集张量
        paperTensor1 = tf.concat(paperArray1,0);

        //塑料图片转换张量
        var plasticLen = parseInt(0.8*plasticLength); //训练集长度
        for (var i = 0; i < plasticLength; i++) {
          var img = document.getElementById('plastic'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < plasticLen){
            //训练集
            plasticArray.push(tensor);
            labelTensor.push(0,1,0,0);
          }else{
            //验证集
            plasticArray1.push(tensor);
            labelTensor1.push(0,1,0,0);
          }
        }
        plasticTensor = tf.concat(plasticArray,0);
        plasticTensor1 = tf.concat(plasticArray1,0);

        //玻璃图片转换张量
        var glassLen = parseInt(0.8*glassLength); //训练集长度
        for (let i = 0; i < glassLength; i++) {
          var img = document.getElementById('glass'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < glassLen){
            //训练集
            glassArray.push(tensor);
            labelTensor.push(0,0,1,0);
          }else{
            //验证集
            glassArray1.push(tensor);
            labelTensor1.push(0,0,1,0);
          }
        }
        glassTensor = tf.concat(glassArray,0);
        glassTensor1 = tf.concat(glassArray1,0);

        //厨余图片转换张量
        var kitchenLen = parseInt(0.8*kitchenLength); //训练集长度
        console.log(kitchenLen);
        for (let i = 0; i < kitchenLength; i++) {
          var img = document.getElementById('kitchen'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < kitchenLen){
            //训练集
            kitchenArray.push(tensor);
            labelTensor.push(0,0,0,1);
          }else{
            //验证集
            kitchenArray1.push(tensor);
            labelTensor1.push(0,0,0,1);
          }
        }
        kitchenTensor = tf.concat(kitchenArray,0);
        kitchenTensor1 = tf.concat(kitchenArray1,0);


        var arrLength = paperLength + plasticLength + glassLength + kitchenLength;
        var traLabelLen = paperLen + plasticLen + glassLen + kitchenLen;
        var valLabelLen = arrLength - traLabelLen;

        //训练集样本
        traTensor = tf.concat([paperTensor, plasticTensor, glassTensor, kitchenTensor], 0);
        labelTensor = tf.tensor(labelTensor, [traLabelLen, 4]);
        //测试集样本
        valTensor = tf.concat([paperTensor1, plasticTensor1, glassTensor1, kitchenTensor1], 0);
        labelTensor1 = tf.tensor(labelTensor1, [valLabelLen, 4]);

        // console.log(labelTensor);
        // tf.print(labelTensor);

        // const optimizer = tf.train.adam(parseFloat(this.$data.setLearnRate));
        const optimizer = 'rmsprop';
        model.compile({
          optimizer,
          loss: 'categoricalCrossentropy',
          metrics: ['accuracy'],
        });
        console.log(model.summary());
        const batchSize = parseInt(this.$data.setBatchSize);
        const epochs = parseInt(this.$data.setEpoch);

        // console.log(batchSize);
        // console.log(epochs);
        // console.log(this.$data.setLearnRate);

        //简单模型训练
        var history = {};
        var _this = this;
        async function train(){
          history = await model.fit(traTensor, labelTensor, {
            batchSize,
            epochs,
            validationData: [valTensor, labelTensor1],
            shuffle: true,
          });
          _this.$data.model3 = model;
          console.log(history);
          //获取模型训练结束的时间戳
          let time2 = new Date().getTime();

          var timeLen  = ((time2- time1)/1000/60).toFixed(3);
           //显示模型准确率
           var acc = history.history.val_acc;
          _this.$data.simpleModelAcc = parseInt(acc[acc.length-1].toFixed(4)*100);

          //关闭动画
          if(history){
            _this.$data.centerDialogVisible = false;
          }
          console.log(acc);
          var jsonParam={
            accuracy:_this.$data.simpleModelAcc,
            activation:_this.$data.activation1,      //激活函数
            model_struct:_this.$data.fullLayerValue+'层全连接网络',    //层数
            model_type:'简单模型',                  //简单  复杂
            train_consume:timeLen
          }

          var result=await model.save('http://192.168.31.103:2444/ModelCenter/uploadMyModel?user_id='+_this.$data.user_info.id)
          axios.post('http://192.168.31.103:2444/ModelCenter/uploadModelInfo',qs.stringify(jsonParam)).then(function (response) {
            console.log(response);
          })
        }
        train();
      },
      createComplexModel(){
        let time1 = new Date().getTime();
        //训练动画打开
        this.$data.centerDialogVisible = true;

        //将数据发给模型测试组件
        var category = {
          catg_1:this.$data.category1,
          catg_2:this.$data.category2,
          catg_3:this.$data.category3,
          catg_4:this.$data.category4,
        }
        // this.$store.state.rubbishName = category;

        //存储图片标签
        axios.post('http://192.168.31.103:2444/CatgCenter/uploadMyCategory', qs.stringify(category))
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });

        console.log(this.$data.convoNetValue);
        console.log(this.$data.activation2);

        var _this = this;

        //创建复杂模型
        if(this.$data.convoNetValue == 3){
          //创建3层卷积神经网络
          this.$data.model2 = createComplexModel(3, this.$data.activation2);
        }else if(this.$data.convoNetValue == 4){
          //创建4层卷积神经网络
          this.$data.model2 = createComplexModel(4, this.$data.activation2);
        }else{
          //创建5层卷积神经网络
          this.$data.model2 = createComplexModel(5, this.$data.activation2);
        }

        //获取需要创建的模型
        var model = this.$data.model2;
        //复杂模型训练过程
        //加载图片数据
        //训练集张量
        var paperTensor;
        var plasticTensor;
        var glassTensor;
        var kitchenTensor;

        //验证集张量
        var paperTensor1;
        var plasticTensor1;
        var glassTensor1;
        var kitchenTensor1;

        //训练集
        var paperArray = [];
        var plasticArray = [];
        var glassArray = [];
        var kitchenArray = [];
        //验证集
        var paperArray1 = [];
        var plasticArray1 = [];
        var glassArray1 = [];
        var kitchenArray1 = [];

        var paperLength = this.$data.paperImgs.length;
        var plasticLength = this.$data.plasticImgs.length;
        var glassLength = this.$data.glassImgs.length;
        var kitchenLength = this.$data.kitchenImgs.length;

        //所有图片的张量
        var traTensor; //训练集
        var valTensor; //测试集
        //训练集标签
        var labelTensor = [];
        //验证集标签
        var labelTensor1 = [];

        //图片数据获取并转换为张量
        //纸类图片转换张量
        var paperLen = parseInt(0.8*paperLength); //训练集长度
        for (var i = 0; i < paperLength; i++) {
          var img = document.getElementById('paper'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);
          if(i < paperLen){
            //训练集
            paperArray.push(tensor);
            labelTensor.push(1,0,0,0);
          }else{
            //验证集
            paperArray1.push(tensor)
            labelTensor1.push(1,0,0,0);
          }
        }
        // console.log(paperArray1.length + paperArray.length);
        //训练集张量
        paperTensor = tf.concat(paperArray,0);
        //验证集张量
        paperTensor1 = tf.concat(paperArray1,0);

        //塑料图片转换张量
        var plasticLen = parseInt(0.8*plasticLength); //训练集长度
        for (var i = 0; i < plasticLength; i++) {
          var img = document.getElementById('plastic'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < plasticLen){
            //训练集
            plasticArray.push(tensor);
            labelTensor.push(0,1,0,0);
          }else{
            //验证集
            plasticArray1.push(tensor);
            labelTensor1.push(0,1,0,0);
          }
        }
        plasticTensor = tf.concat(plasticArray,0);
        plasticTensor1 = tf.concat(plasticArray1,0);

        //玻璃图片转换张量
        var glassLen = parseInt(0.8*glassLength); //训练集长度
        for (let i = 0; i < glassLength; i++) {
          var img = document.getElementById('glass'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < glassLen){
            //训练集
            glassArray.push(tensor);
            labelTensor.push(0,0,1,0);
          }else{
            //验证集
            glassArray1.push(tensor);
            labelTensor1.push(0,0,1,0);
          }
        }
        glassTensor = tf.concat(glassArray,0);
        glassTensor1 = tf.concat(glassArray1,0);

        //厨余图片转换张量
        var kitchenLen = parseInt(0.8*kitchenLength); //训练集长度
        console.log(kitchenLen);
        for (let i = 0; i < kitchenLength; i++) {
          var img = document.getElementById('kitchen'+i);
          let imgTensor =tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0);
          //将图像像素归一化
          tensor  = tf.div(tensor,255);

          if(i < kitchenLen){
            //训练集
            kitchenArray.push(tensor);
            labelTensor.push(0,0,0,1);
          }else{
            //验证集
            kitchenArray1.push(tensor);
            labelTensor1.push(0,0,0,1);
          }
        }
        kitchenTensor = tf.concat(kitchenArray,0);
        kitchenTensor1 = tf.concat(kitchenArray1,0);


        var arrLength = paperLength + plasticLength + glassLength + kitchenLength;
        var traLabelLen = paperLen + plasticLen + glassLen + kitchenLen;
        var valLabelLen = arrLength - traLabelLen;

        //训练集样本
        traTensor = tf.concat([paperTensor, plasticTensor, glassTensor, kitchenTensor], 0);
        labelTensor = tf.tensor(labelTensor, [traLabelLen, 4]);
        //测试集样本
        valTensor = tf.concat([paperTensor1, plasticTensor1, glassTensor1, kitchenTensor1], 0);
        labelTensor1 = tf.tensor(labelTensor1, [valLabelLen, 4]);

        // const optimizer = 'rmsprop';
        // const LEARNING_RATE = 0.15;

        const optimizer = tf.train.adam(parseFloat(this.$data.setLearnRate1));
        model.compile({
          optimizer,
          loss: 'categoricalCrossentropy',
          metrics: ['accuracy'],
        });
        // tf.print(model);
        console.log(model.summary());
        const batchSize = parseInt(this.$data.setBatchSize1);
        const epochs = parseInt(this.$data.setEpoch1);

        //复杂模型训练
        async function train(){

          const history =await model.fit(traTensor, labelTensor, {
            batchSize,
            epochs,
            validationData:[valTensor, labelTensor1],
            shuffle: true,
          });

          console.log(history);
          let time2 = new Date().getTime();
          var timeLen = ((time2- time1)/1000/60).toFixed(3);
          //关闭动画
          if(history){
            _this.$data.centerDialogVisible = false;
          }


          //显示模型准确率
          var acc = history.history.val_acc;
          _this.$data.simpleModelAcc1 = parseInt(acc[acc.length-1].toFixed(4)*100);
          _this.$data.model4 = model;

          var jsonParam={
            accuracy:_this.$data.simpleModelAcc1,       //准确率
            activation:_this.$data.activation2,      //激活函数
            model_struct:_this.$data.convoNetValue+'层卷积网络',    //层数
            model_type:'复杂模型',                  //简单  复杂
            train_consume:timeLen,      //训练时间
          }
          var result=await model.save('http://192.168.31.103:2444/ModelCenter/uploadMyModel?user_id='+_this.$data.user_info.id)
          axios.post('http://192.168.31.103:2444/ModelCenter/uploadModelInfo',qs.stringify(jsonParam)).then(function (response) {
            console.log(response);
          })
        }

        train();


      },
      triggerFileSelect(){
        var btn=document.getElementById("userFile");
        btn.click();
      },
      //选择图片进行测试
      handleSelect(e){
        var file = document.getElementById('userFile').files[0];
        var img = document.getElementById('testImg');
        let _this = this;
        let reader = new FileReader();
        var model = {};
        reader.readAsDataURL(file);
        reader.onloadend = function () {
          _this.showIndex = false;
          //showImgSrc是用户上传测试图片的绝对路径
          // _this.showImgSrc= this.result;
          img.src = this.result;
          predict();
        }
        if(this.$data.selectModelValue == 1){
          //选择简单模型进行测试
          model = this.$data.model3;
        }else {
          //选择复杂模型进行测试
          model = this.$data.model4;
        }
        //将测试图片转化为张量
        async function predict(){
          var img = await document.getElementById('testImg');
          let imgTensor =await tf.browser.fromPixels(img);
          imgTensor = tf.image.resizeBilinear(imgTensor, [56,56]).toFloat();
          let tensor = imgTensor.expandDims(0)
          const prediction = model.predict(tf.div(tensor,255)).dataSync();
          console.log(prediction);

          var index;
          var element = prediction[0];
          for (var i = 0; i < prediction.length; i++) {
            if(prediction[i] >= element){
              element = prediction[i];
              index = i;
            }
          }
          //预测出来的类型下标
          console.log(index);
          var rubbishName = [_this.$data.category1, _this.$data.category2, _this.$data.category3, _this.$data.category4];
          _this.$data.showResult = rubbishName[index];
        }
      },
      ParmChange(e){
        if(e=="1")
        {
           this.$data.showParmKind=true;
        }
        else{
          this.$data.showParmKind=false;
        }
      }
    },
    beforeRouteLeave (to, from, next) {
      const answer = window.confirm("当前页面数据未保存，确定要离开？");
      if (answer) {
        next();
      } else {
        next(false);
      }
    },
    mounted(){
      var _this=this;
      axios.get("http://192.168.31.103:2444/LoginCenter/getUserInfo").then(function(res){
        console.log(res)
         if(res.data=="")  _this.$router.push({path:"/login"})
         else{
           _this.$data.user_info.id=res.data.user_id;
           _this.$data.user_info.nickname=res.data.nickname;
         }
      });
      //将数据发给模型测试组件
      var category = {
          category1:this.$data.category1,
          category2:this.$data.category2,
          category3:this.$data.category3,
          category4:this.$data.category4,
        }
      this.$store.state.rubbishName = category;
      window.onbeforeunload = function(e) {
        if (_this.$route.fullPath == '/Practice') {
          e = e || window.event;
          // 兼容IE8和Firefox 4之前的版本
          if (e) {
            e.returnValue = "关闭提示";
          }
          // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
          return "关闭提示";
        } else {
          window.onbeforeunload = null;
        }
      };
    }
  }

  </script>

  <style scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }

  .modelBox{
    margin-top: 20px;
    height: 500px;
  }
  .layerList{
    display: block;
    float: left;
    width: 200px;
    text-align: left;
  }
  .foundList{
    display: block;
    float: right;
    width: 258px;
    /* background-color: aqua; */
    height: 350px;
    border:1px solid #000;
    overflow-y:scroll;
  }
  ul{
    list-style-type: none;
    display:inline-block;
    padding: 0;
  }
  li{
    text-align: center;
    width: 180px;
    height: 80px;
    line-height: 80px;
    font-size: 25px;
  }
  li i{
    float: right;
    line-height: 80px;
    cursor:pointer;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .simpleModel{
    margin-top: 35px;
  }
  .complexModel{
    margin-top: 20px;
  }

  .showTraining{
    border: 1px solid #000;
    border-radius :10px;
    background-color: rgb(233, 231, 231);
    height: 350px;
    line-height: 350px;
  }
  .showModel img{
    margin-top: 5px;
    border-radius: 5px;
  }
  .showImg{
    border: 1px solid #000;
    border-radius :10px;
    background-color: rgb(233, 231, 231);
    height: 350px;
  }
  .chooseImg{
    display:inline-block;
    margin-top: 10px;
  }
  .numInput{
      margin-top: 5px;
      width: 221.4px !important;
  }
  .cagetoryInput{
      width: 150px !important;
  }
  .el-dialog{
    color: #FAFAFA !important;
  }
  </style>
